package com.springboot.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig<V> {

    @Bean("redisTemplate")
    public RedisTemplate<String, V> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, V> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置key的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化方式
        Jackson2JsonRedisSerializer<V> valueSerializer = new Jackson2JsonRedisSerializer<>(getObjectClass());
        valueSerializer.setObjectMapper(new ObjectMapper());
        template.setValueSerializer(valueSerializer);

        // 设置hash的key的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(valueSerializer);

        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 在这里添加消息监听器
        // container.addMessageListener(new YourMessageListener(), new PatternTopic("your-topic"));
        return container;
    }

    // Helper method to get the type of the V generic type
    private Class<V> getObjectClass() {
        return (Class<V>) Object.class;
    }
}
